package com.xzcs.service.weixin.expand;

import com.xzcs.util.common.DateUtils;
import com.xzcs.util.common.GsonUtils;
import com.xzcs.util.common.StringUtils;
import com.xzcs.util.net.HttpClientUtils;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc: 淘宝优惠券
 * @author: chang
 * @date: 2017/10/31
 */
public class TbkYhqServiceImpl implements ExpandService {
    public String URL = "http://gw.api.taobao.com/router/rest";
    public String APPKEY = "24904312";
    public String SECRET = "d6322125afa84de3eacf025bee1a5f9d";
    public Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public String excute(HttpServletRequest request, WxMpXmlMessage inMessage) {
        String responseMsg = "";
        String content = inMessage.getContent();
        StringBuffer buffer = new StringBuffer();
        if (content.startsWith("优惠券")) {
            String keyWorkd = content.replaceAll("优惠券", "").trim();

            Map<String, String> params = new HashMap<String, String>();
            params.put("method", "taobao.tbk.dg.material.optional");
            params.put("app_key", APPKEY);
            params.put("timestamp", DateUtils.getToday("yyyy-MM-dd HH:mm:ss"));
            params.put("format", "json");
            params.put("v", "2.0");
            //params.put("session", "6100727918f5d6cf0d862a15b7b362759f4199cda5829c0908909555");
            params.put("sign_method", "md5");
            params.put("adzone_id", "634264461");
            params.put("site_id", "45604335");
            params.put("q", keyWorkd);
            params.put("start_tk_rate", "500");//佣金下限5.00%
            params.put("sort", "tk_rate_desc");//佣金降序
            params.put("has_coupon", "true");//有优惠券
            params.put("need_free_shipment", "true");//包邮
            String sign = "";
            try {
                sign = TaoBaoUtils.signTopRequest(params, SECRET, "MD5");
            } catch (IOException e) {
                logger.error("淘宝接口签名错误：", e);
            }
            params.put("sign", sign);

            HttpClientUtils http = new HttpClientUtils("UTF-8");
            String result = http.doPostRequest(URL, params, null, null, false);

            Map<String, Object> taob = (Map<String, Object>) GsonUtils.stringToMap(result);
            Map<String, Object> tbk_dg_material_optional_response = (Map<String, Object>) taob.get("tbk_dg_material_optional_response");
            if (null != tbk_dg_material_optional_response && !tbk_dg_material_optional_response.isEmpty()) {
                Map<String, Object> results = (Map<String, Object>) tbk_dg_material_optional_response.get("result_list");
                if (null != results && !results.isEmpty()) {
                    List<Map<String, Object>> list = (List<Map<String, Object>>) results.get("map_data");
                    Map<String, Object> product = list.get(0);

                    String title = StringUtils.get(product, "title");
                    //String reserve_price = StringUtils.get(product, "reserve_price");
                    String zk_final_price = StringUtils.get(product, "zk_final_price");
                    String coupon_click_url = StringUtils.get(product, "coupon_share_url");
                    String coupon_info = StringUtils.get(product, "coupon_info");
                    Map<String, Object> small_images = (Map<String, Object>) product.get("small_images");
                    List<String> images = (List<String>) small_images.get("string");
                    coupon_click_url = coupon_click_url.startsWith("http") ? coupon_click_url : "https:"+coupon_click_url;

                    params = new HashMap<String, String>();
                    params.put("method", "taobao.tbk.tpwd.create");
                    params.put("app_key", APPKEY);
                    params.put("timestamp", DateUtils.getToday("yyyy-MM-dd HH:mm:ss"));
                    params.put("format", "json");
                    params.put("v", "2.0");
                    params.put("sign_method", "md5");
                    params.put("user_id", "908909555");
                    params.put("text", title);
                    params.put("url", coupon_click_url);
                    if (null != images && images.size()>0) {
                        params.put("logo", images.get(0));
                    }
                    params.put("ext", "{'title': '"+title+"'}");
                    try {
                        sign = TaoBaoUtils.signTopRequest(params, SECRET, "MD5");
                    } catch (IOException e) {
                        logger.error("淘宝接口签名错误：", e);
                    }
                    params.put("sign", sign);
                    result = http.doPostRequest(URL, params, null, null, false);

                    Map<String, Object> tpwd = (Map<String, Object>) GsonUtils.stringToMap(result);
                    Map<String, Object> tbk_tpwd_create_response = (Map<String, Object>) tpwd.get("tbk_tpwd_create_response");
                    Map<String, Object> data = (Map<String, Object>) tbk_tpwd_create_response.get("data");
                    String model = StringUtils.get(data, "model");

                    buffer.append(title).append("\n")
                            //.append("【在售价】"+reserve_price+"元").append("\n")
                            .append("【在售价】"+zk_final_price+"元").append("\n")
                            .append("【优惠券】"+coupon_info).append("\n")
                            .append("---------------").append("\n")
                            .append("复制信息，"+model+"，打开【手机淘宝】即可查看");

                } else {
                    buffer.append("未查询到【"+keyWorkd+"】优惠券信息，请查询其他商品信息");
                }
            } else {
                buffer.append("未查询到【"+keyWorkd+"】优惠券信息，请查询其他商品信息");
            }
        } else {
            buffer.append("优惠券+商品关键字，例如'优惠券女鞋'");
        }
        WxMpXmlOutMessage outMessage = WxMpXmlOutMessage.TEXT()
                .content(buffer.toString())
                .fromUser(inMessage.getToUser())
                .toUser(inMessage.getFromUser()).build();
        responseMsg = outMessage.toXml();
        return responseMsg;
    }
}
